var table = layui.table;
var pop3=""; //控制显示的邮箱邮件
var leftPage="";//控制左边分页
var search="";//控制简单查询分页
var email_deploy="";//用户设置
var noready=0;//未读邮件
var form = layui.form;
$ = layui.jquery;
var yidongControl=0;//0是用户邮件，1是切换用户邮件，2是客户箱
var id = getQueryVariable("id");
var isread=1;//等于0时，读邮件变已读  等于1时，不改变状态
var proPost=0;//等于0时，主题RE前置，等于1时，主题RE后置
function  OnChanged(s) {
    isread=s
}
function  changeprePost(s1) {
    proPost=s1;
}

//客户箱结构树
function getEmailCustomerJson(jsons) {//第一层，根节点，客户
    if(jsons!=null&&jsons!=""){
        let tmpitem=[]
        // key  jsons[key]
        for(let i in jsons){
            let tmparr={}
            tmparr["value"]=jsons[i]["code"];
            tmparr["name"]=jsons[i]["name"];
            tmparr["title"]=jsons[i]["name"];
            if(jsons[i]["list"]!=null&&jsons[i]["list"]!=""){
                tmparr["children"]=  getEmailCustomerJson1(jsons[i]["list"]);
                tmparr["children"].unshift({"value":"start:"+jsons[i]["code"],"name":jsons[i]["name"],"title":jsons[i]["name"]})
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }else{
        return null
    }
}
function getEmailCustomerJson1(jsons) {//第二层，客户联系人箱
    if(jsons!=null&&jsons!=""){
        let tmpitem=[]
        for(let i in jsons){
            // key  jsons[key]
            let tmparr={}
            tmparr["value"]=jsons[i]["email"];
            tmparr["name"]=jsons[i]["name"];
            tmparr["title"]=jsons[i]["name"];
            tmpitem.push(tmparr)}
        return tmpitem
    }else{
        return null
    }
}

//进入页面

function successFu(data) {
    var tbody = $(".email_table").children("tbody");
    tbody.html("");
    var emails = data.list;//邮件结果集合

    for (let i in emails) {
        var o = {};
        o.email_id = emails[i].email_id;
        o.message_id = emails[i].message_id;
        o.message_server = emails[i].message_server;
        o.Parent_id = emails[i].Parent_id;
        o.interForw_id = emails[i].interForw_id;
        o.answer_id = emails[i].answer_id;
        o.forw_id = emails[i].forw_id;
        o.email_class = emails[i].email_class;
        o.subject = emails[i].subject;
        o.addresser = emails[i].addresser;
        o.senderAddresser = emails[i].senderAddresser;
        o.recipientName = emails[i].recipientName;
        o.recipientAddress = emails[i].recipientAddress;
        o.copyer = emails[i].copyer;
        o.copyAddress = emails[i].copyAddress;
        o.darkSendAddress = emails[i].darkSendAddress;
        o.emailSize = emails[i].emailSize;
        o.account = emails[i].account;
        o.recDate = emails[i].recDate;
        o.sendDate = emails[i].sendDate;
        o.createDate = emails[i].createDate;
        o.charset = emails[i].charset;
        o.sendSuccess = emails[i].sendSuccess;
        o.pop3_id = emails[i].pop3_id;
        o.readStatue = emails[i].readStatue;
        o.hasAttaNum = emails[i].hasAttaNum;
        o.adjunctNum = emails[i].adjunctNum;
        o.readyStatue = emails[i].readyStatue;
        o.tag = emails[i].tag;
        o.star = emails[i].star;
        result.push(o);
    }
}

function getpop3(accid) {//type=0时，查询全部的IDS  不等于-1时，查询改账户下的所有IDS

    $.ajax({
        url: 'email/showAccByCode?accid='+accid,
        async: false, // 同步
        // contentType: "application/json; charset=utf-8",
        // dataType: "json",
        // date:{
        //     "accid" : accid,
        // },
        success: function (data) {
            pop3=data.data;
        },
    });
}
//分页
//存储显示的数据
var result = new Array();
//进入页面设置
function regress(){
    getnoRead()
    showBox()
    getpop3(0);
    getsmtp()
    getpop3ID()
    page();
    getdeploy()
}
$(document).ready(function () {
    getnoRead()
    showBox()
    getpop3(0);
    getsmtp()
    getpop3ID()
    page();
    getdeploy()
    selectEmailReadNum()
    if(id==3){//今日未读邮件

    }
    if(id==2){//今日发送邮件
        var d = new Date();
        var gaoji= {
            "pop3s":pop3,
            "subject":null,
            "tag" :null,
            "recipientName" :null,
            "recipientAddress" :null,
            "recDate" :null,
            "addresser" :null,
            "senderAddresser" :null,
            "sendDate" :d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" 00:00:00"+" - "+d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" 23:59:59",
            "isAdjunct":"不限",
            "adjunct" :null,
            "sub":null,
            "proPost":proPost
        }
        showGaojiMailList(gaoji);
    }
    if(id==1){//今日收到邮件
        var d = new Date();
        var gaoji= {
            "pop3s":pop3,
            "subject":null,
            "tag" :null,
            "recipientName" :null,
            "recipientAddress" :null,
            "recDate" :d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" 00:00:00"+" - "+d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" 23:59:59",
            "addresser" :null,
            "senderAddresser" :null,
            "sendDate" :null,
            "isAdjunct":"不限",
            "adjunct" :null,
            "sub":null,
            "proPost":proPost
        }
        showGaojiMailList(gaoji);
    }


});


function getnoRead() {
    $.ajax({
        url: 'email/selectnoRead',
        type: 'GET',
        async: false, // 同步
        success: function (data) {
            noready=data.data
        },
    });
}

function selectEmailReadNum() {
    $.ajax({
        url: 'email/selectEmailReadNum?pop3s='+pop3,
        type: 'GET',
        async: false, // 同步
        success: function (data) {
            var num=data.data
            for(let i in num){
                $("#num"+i).append("<span style='float:right;'>"+num[i]+"</span>")
            }
        },
    });
}

function  getsmtp() {
    $.ajax({
        url: 'email/selectSmtp',
        type: 'GET',
        async: false, // 同步
        success: function (data) {

        },
    });
}
//获取用户设置
function getdeploy() {
    $.ajax({
        url: 'email/showdeploy',
        type: 'GET',
        async: false, // 同步
        success: function (data) {
            email_deploy=data.data
        },
    });

}

//用户所属邮箱控制显示
function getpop3ID() {
    $.ajax({
        url: 'email/selectAcc',
        success: function (data) {
            get(data);
        },
    });
}
//显示邮箱信息到页面
function get(date) {

    var acc = date.data;
    for(let i in acc){
        $('#user-pop3').append("<option value='"+acc[i].account_id+"'>"+acc[i].account_name+"</option>");
    }
    form.render();
}
//监听邮箱选择器更改方法
form.on('select(user-pop3)', function(data){

    var elem = data.value; //得到select的值
    if(elem=="全部"){
        getpop3(0);
    }else{
        getpop3(elem);
    }
    page();
});
//左边箱体控制
function changeleftPage(left) {
    search="";
    leftPage=left;
    page();

}

//分页控制
function page(){
    showMailList();
}
$("#shouxin").click(function(){
    //待定
});
$("#gaoji").click(function(){
    layer.open({
        type: 2
        ,title: false //不显示标题栏
        ,closeBtn: false
        ,area:  ['800px', '700px']
        ,shade: 0.8
        ,btn: ['重置', '取消','确定']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,content: ['views/jsp/BasicData/email/gaoji.jsp','no']
        ,btn2:function (index,layero) {
            layer.closeAll();
        }
        ,btn3:function (index,layero) {
            var res = window["layui-layer-iframe"+index].callbackdata();
            //打印返回的值，看是否有我们想返回的值。
            getpop3(0);
            var gaoji= {
                "pop3s":pop3,
                "subject":res.subject,
                "tag" : res.tag,
                "recipientName" :res.recipientName,
                "recipientAddress" :res.recipientAddress,
                "recDate" : res.recDate,
                "addresser" : res.addresser,
                "senderAddresser" : res.senderAddresser,
                "sendDate" : res.sendDate,
                "isAdjunct":res.isAdjunct,
                "adjunct" : res.adjunct,
                "sub":res.sub,
                "proPost":proPost
            }
            showGaojiMailList(gaoji);
            layer.closeAll();
        }
    });

});

$(".s_email").click(function(){
    var c = $(this).attr('c');
    var s = $(this).children('i:eq(0)').text();
    var s1 = $("#xjt").text();
    var s2 = $("#yjt").text();
    if(s === s1){
        //隐藏
        $("tr["+c+"]").hide();
        $(this).children('i:eq(0)').text(s2);
    }else{
        //显示
        $("tr["+c+"]").show();
        $(this).children('i:eq(0)').text(s1);
    }
});

$("#closeFast").click(function(){
    $(".fast_priview").animate({left:'10000px'});
});

$(document).on('mouseenter',"#showSetting",function(){
    $(".showMore").show();
    if($(".showMore").attr("children")){

    }else{
        var l = $(".showMore").parent().parent().parent().parent().position().left-130;
        $(".showMore").parent().parent().parent().parent().css('left',l);
        $(".showMore").attr("children","true");
    }

});
//简单查询
$("#searchBtn").click(function(){
    search= $("#tip").val();
    page();
});


function getTags(tag) {
    var t=tag.split(";")
    var tags=new Array();
    for(var i=0;i<t.length-1;i++){
        var split = t[i].split(",");
        var split2=""
        if(split.length>3){
            for(var j=2;j<split.length;j++){
                split2+=split[j]+","
            }
            split2=split2.substr(0,split2.length-1)
        }else{
            split2=split[2]
        }
        var tagt={
            "id":split[0],
            "color":split[1],
            "title":split2
        }
        tags.push(tagt);
    }
    return tags;
}

//主题显示
function showElement(element){
    var biaoqianHtml = '';
    //标签形式为 1,red,标签1；2,yello,标签2；
    if(element.tag!=null){
        var tags=getTags(element.tag);
        for(let i in tags){
            var tagg=""
            if(tags[i].title.length>10){
                tagg= tags[i].title.substr(0,10)+"......"
            }else{
                tagg=tags[i].title;
            }
            biaoqianHtml+='<span class="layui-badge" style="background-color:'+tags[i].color+';color: #0C0C0C" title="'+tags[i].title+'">'+tagg+'</span>';
        }
    }

    //主题长度处理
    // var sl = 48; //标题栏显示长度
    var subject = element.subject;
    // if (subject.length <= sl) {
    //     var len = sl - subject.length;
    //     subject= subject.substr(0, len);
    // }
    //控制已读未读
    var classzhi = (element.readStatue==0)?"yidu":"weidu";
    //加已读未读图标
    var tubiao=""
    if(classzhi=="yidu"){
        tubiao="<img style='width: 20px'  alt=\"\" src=\"statics/img/read.png\""+">";
    }else{
        tubiao="<img style='width: 20px' alt=\"\" src=\"statics/img/noready.png\""+">";
    }
    //加附件图标
    var futubiao=""
    if(element.adjunctNum>0){
        futubiao="<img style='width: 20px' alt=\"\" src=\"statics/img/adjunct.png\""+">";
    }
    var size=(element.emailSize/1024).toFixed(2)+"kb";
    var xinbiao=(element.star==0)?"<i class=\"layui-icon layui-icon-rate-solid\" onclick='changeXinbiao("+element.email_id+")'></i>":"<i class=\"layui-icon layui-icon-rate-solid yellow\" onclick='changeXinbiao("+element.email_id+")'></i>"
    return ' <div class="widget">'
        +futubiao
        +biaoqianHtml+
        xinbiao+ //星标控制
        '<div class="hwidget"><i title="新增标签" onClick="showBadgeWindow('+element.email_id+',\''+element.tag+'\')">&#xe640;</i></div>'+
        '</div> <a lay-event="showEmail" class='+classzhi+' id='+element.email_id+' >'+tubiao+"&nbsp&nbsp"+subject+'</a>';
}

function changeWeidu(emailid,normal){
    $("#"+emailid).css("fontWeight",normal);
}

//触发行单击事件
table.on('tool(email_table)', function(obj){
    var email = obj.data //得到当前行数据
    if (email.readStatue == 1) {
        email.readStatue = 0;
        changeWeidu(email.email_id, "normal")
    }
    var emails = layui.table.cache["email_table"];
    var ids = '';
    for (let i in emails) {
        ids = ids + emails[i].email_id + ",";
    }
    var lengths = email_deploy.display;    //我这里只是测试判断 0，0为跳转页面 1为弹窗
    if (lengths == 1) {
        //iframe窗
        layer.closeAll();
        layer.open({
            type: 2,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            shade: false,
            area: ['50%', '100%'],
            offset: 'rt', //右下角弹出
            content: ['views/jsp/BasicData/email/detail.jsp?isread='+isread+'&email_id=' + email.email_id + '&ids=' + ids + '&types=2'], //iframe的url，no代表不显示滚动条
            success: function (layero, index) {

            }
        });
    } else {
        parent.intab("views/jsp/BasicData/email/detail.jsp?isread="+isread+"&email_id=" + email.email_id + "&ids=" + ids, "邮件详情")
    }
    $('div[lay-id=email_table] table').attr("class", "layui-table email_table");
});
//
function donef(res, curr, count) {
//     $('.yidu,.weidu').on('click',function(){
//         var thin = this;
//         if(thin.className == "weidu"){
//             thin.className = "yidu";
//         }
//
//         var id = thin.id;
//         var emails=res.data;
//         var ids='';
//         for(let i in emails){
//             ids=ids+emails[i].email_id+",";
//         }
//
//         var lengths =email_deploy.display;    //我这里只是测试判断 0，0为跳转页面 1为弹窗
//         if(lengths == 1){
//             //iframe窗
//             layer.closeAll();
//             layer.open({
//                 type: 2,
//                 title: false,
//                 closeBtn: 0, //不显示关闭按钮
//                 shade: false,
//                 area: ['50%', '100%'],
//                 offset: 'rt', //右下角弹出
//                 content: ['views/jsp/BasicData/email/detail.jsp?email_id='+id+'&ids='+ids+'&types=2'], //iframe的url，no代表不显示滚动条
//                 success: function(layero, index){
//                     console.log(layero, index);
//                 }
//             });
//         }else{
//             parent.intab("views/jsp/BasicData/email/detail.jsp?email_id="+id+"&ids="+ids,"邮件详情")
//         }
//     });
    $('div[lay-id=email_table] table').attr("class","layui-table email_table");
}



//一般分页
function showMailList(){
    table.render({
        elem: '#email_table'
        ,url:"email/showAllEmailByPage"
        ,where:{pop3s:pop3,leftPage:leftPage,search:search,proPost:proPost}
        ,id: 'email_table'
        ,height: $(document).height() - $('#email_table').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits:[50,100,150,200,250,300,500,1000,1500,2000]
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'subject', title:'主题',minWidth:700,sort:true,templet: function(element){ return showElement(element) }}
            ,{field:'s', title:'发件人',width:200,sort:true,templet: function(element){
                    if(element.addresser!=""&&element.addresser!=null){
                        return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+element.addresser+"&lt;"+element.senderAddresser+"&gt;";
                    }else{
                        return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+"&lt;"+element.senderAddresser+"&gt;";
                    }
                }}
            ,{field:'recipientAddress', title:'收件人',width:180,sort:true}
            ,{field:'recDate', title:'日期',width:200,sort:true,templet: function(element){
                    return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>&lt;'+element.recDate+'&gt;';
                }}
            ,{field:'emailSize', title:'大小',width:150,sort:true,templet: function(element){
                    var size=  (element.emailSize)/1024
                    if(size>1024){
                        size=(size/1024).toFixed(2)+"mb";
                    }else{
                        size=size.toFixed(2)+"kb"
                    }
                    return size
                }}
            ,{field:'adjunctNum', title:'附件数',width:100,sort:true}
        ]]

        ,toolbar: "<div>用户表:未读邮件"+noready+"封</div>"
        ,title:"邮件"
        ,done:function (res, curr, count) {
            donef(res, curr, count);
        }
    });
}

//高级查询分页
function showGaojiMailList(searchGaoji){
    table.render({
        elem: '#email_table'
        ,url:"email/showGaojiEmailByPage"
        ,where:searchGaoji
        ,id: 'email_table'
        ,height: $(document).height() - $('#email_table').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits:[50,100,150,200,250,300,500,1000,1500,2000]
        ,cols: [[
            {checkbox: true, fixed: true}

            ,{field:'subject', title:'主题',sort:true,templet: function(element){ return showElement(element) }}
            ,{field:'senderAddresser', title:'发件人',width:200,sort:true,templet: function(element){
                    if(element.addresser!=""&&element.addresser!=null){
                        return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+element.addresser+"&lt;"+element.senderAddresser+"&gt;";
                    }else{
                        return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+"&lt;"+element.senderAddresser+"&gt;";
                    }
                }}
            ,{field:'recipientAddress', title:'收件人',sort:true,width:180,sort:true}
            ,{field:'recDate', title:'日期',width:220,sort:true,templet: function(element){
                    return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>&lt;'+element.recDate+'&gt;';
                }}
            ,{field:'emailSize', title:'大小',width:150,sort:true,templet: function(element){
                    var size=  (element.emailSize)/1024
                    if(size>1024){
                        size=(size/1024).toFixed(2)+"mb";
                    }else{
                        size=size.toFixed(2)+"kb"
                    }
                    return size
                }}
            ,{field:'adjunctNum', title:'附件数',width:100,sort:true}
        ]]
        ,toolbar: "<div>用户表:未读邮件"+noready+"封</div>"
        ,title:"邮件"
        ,done:function (res, curr, count) {
            donef(res, curr, count);
        }
    });
}


//监听复选框
table.on('checkbox(email_table)', function (data) {
    if(yidongControl==2){
        $(".baryc").css("display","none");
    }else{
        var email_tabledata = table.checkStatus("email_table").data;
        if(email_tabledata.length == 0){
            $(".baryc").css("display","none");
        }else{
            $(".baryc").css("display","inline-block");
        }
    }
});
//取消
function qx() {
    $(".baryc").css("display","none");
}
//星标修改
function changeXinbiao(emailid){
    $.ajax({
        url: 'email/changeXinbiao',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {
            "emailID":emailid
        },
        success: function (date) {
            layer.msg("星标修改成功")
        },
    });
}
/**
 * 显示新增编辑标签窗口
 */
function deleteTag(email_id,id) {
    layer.closeAll()
    $.ajax({
        url: 'email/deleteBiaoqian',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {
            "emailID":email_id,
            "id":id
        },
        success: function (data) {
            var tag= data.data.tag;
            var emailID= data.data.emailID;
            showBadgeWindow(emailID,tag)
        },
    });
}
function refrashTag() {
    layer.closeAll()
    // 刷新
    $(".layui-laypage-btn")[0].click();
}

function showBadgeWindow(email_id,tag){
    var biaoqian="";
    if(tag!=null){
        var tags=getTags(tag);
        for(let i in tags){
            biaoqian+= "<span class=\"layui-badge\" style=\"background-color:"+tags[i].color+";color: #0C0C0C\">"+tags[i].title+"</span><a style='text-align: right' onclick=\"deleteTag("+email_id+","+tags[i].id+")\">删除标签</a><hr>";
        }
    }
    var html="<div id=\"BadgeWindow\" <div class=\"badge-window\"><div><input type=\"text\" placeholder=\"标签名称\"></div><div class='cs'>"+
        biaoqian
        +
        "</div><div><a onclick=\"showCreateBadgeWindow("+email_id+")\"><i class=\"icon\">&#xe60f;</i>新增</a><a onclick=\"refrashTag()\">确认</a></div></div></div>";
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: false,
        content: html
    });
}

function showCreateBadgeWindow(email_id){
    layer.open({
        btn: ['确定', '取消'],
        type: 1,
        title:'新增标签',
        skin: 'layui-layer-rim', //加上边框
        area: ['420px', '240px'], //宽高
        content: $("#CreateBadgeWindow"),
        shadeClose:false,
        btn1:function (index,layero) {
            var title=$("#tagTitle").val();
            var color=$("#test-form-input").val();
            addTag(email_id,title,color);
        }
    });
    $("#CreateBadgeWindow").show();
}
function addTag(email_id,title,color){
    layer.closeAll();
    $.ajax({
        url: 'email/addTag',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {
            "emailID":email_id,
            "title":title,
            "color":color
        },
        success: function (data) {
            var tag= data.data.tag;
            var emailID= data.data.emailID;
            showBadgeWindow(emailID,tag)
        },
    });
}

$(function(){
    $(document).on('click',".layui-icon-rate-solid",function(){
        if($(this).hasClass('yellow')){
            $(this).removeClass('yellow');
        }else{
            $(this).addClass('yellow');
        }
    });
})

function quanxuan(type,t){
    if(type === 'all'){
        if(t.checked){
            $(".email_table input[type=checkbox]").attr("checked","checked");
        }else{
            $(".email_table input[type=checkbox]").removeAttr("checked");
        }
    }else{
        if(t.checked){
            $("input[type=checkbox]["+type+"]").attr("checked","checked");
        }else{
            $("input[type=checkbox]["+type+"]").removeAttr("checked");
        }
    }
}

function showDefineXx(type){
    var url = type?'views/jsp/BasicData/email/defineZdx.jsp':'views/jsp/BasicData/email/defineXinxiang.jsp';
    var area = type?['1000px', '600px']:['600px', '400px'];
    layer.open({
        type: 2
        ,title: false //不显示标题栏
        ,closeBtn: false
        ,area:  area
        ,shade: 0.8
        ,btn: ['确定']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,content: [url,'no']
        ,success: function(layero){


        }
    });
}


//老代码
layui.use(["index",'laypage', 'layer','tree','util','colorpicker','dropdown','tagsInput'], function(){


    if(id==4){//跳转客户箱
        //views/jsp/BasicData/email/index.jsp?id=4&custorID=abc
        var custorID=getQueryVariable("custorID");
        //进行跳转
        resetControl(2)
        var element = layui.element;
        //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
        // var layid = location.hash.replace(/^#test1=/, '');
        element.tabChange('test1', "supplier"); //假设当前地址为：http://a.com#test1=222，那么选项卡会自动切换到“发送消息”这一项

        $.ajax({
            url: 'customer/selectEmailCustomConCateByCode?code='+custorID,
            type: 'POST',
            success: function (date) {
                //返回的date，插入树中
                if(date.data!=null&&date.data!=""){
                    var costomerTree=getEmailCustomerJson(date.data)
                    customerTree(costomerTree)
                }else{
                    layer.msg("该客户没有联系人")
                }
            },
        });
        //页面切换
    }

    var laypage = layui.laypage
        ,layer = layui.layer
        ,tree = layui.tree
        ,colorpicker = layui.colorpicker,dropdown = layui.dropdown;
    $ = layui.jquery
    var tagsInput = layui.tagsInput
    var type=1;//0是管理员，1是普通用户
    var admin=getdictionary(6,59);
    for(let i in admin){
        if(user.code==admin[i].name){
            type=0
        }
    }
    var AllUserCode="" //当前登录用户及登录用户管理到用户的code，以","进行分割

    //表单赋值
    colorpicker.render({
        elem: '#test-form'
        ,color: '#1c97f5'
        ,done: function(color){
            $('#test-form-input').val(color);
        }
    });

    laypage.render({
        elem: 'demo7'
        ,count: 100
        ,limits:[15,30,45]
        ,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
        ,jump: function(obj){

        }
    });
    //内部联系人箱和切换用户箱获取结构树
    function getAllJson(jsons) {
        if(jsons!=null&&jsons!=""){
            let tmpitem=[]
            for (let item of jsons) {
                let tmparr={}
                tmparr["value"]=item["code"];
                tmparr["name"]=item["name"];
                tmparr["title"]=item["name"];
                if(item["users"]){
                    for(let it of item["users"]){
                        item["list"].push(it)
                    }
                }
                if(item["list"] && item["list"].length){
                    tmparr["children"]=  getAllJson(item["list"]);
                    tmpitem.push(tmparr)
                }else{
                    tmpitem.push(tmparr)
                }

            }
            return tmpitem
        }else{
            return null
        }
    }
    //内部联系人箱和切换用户箱获取结构树
    //当前登录用户及所管理的所有人的code
    function getUserJson(jsons) {
        if(jsons!=null&&jsons!=""){
            let tmpitem=[]
            for (let item of jsons) {
                let tmparr={}
                tmparr["value"]=item["code"];
                if(item["code"].substr(0,3)=="RKB"){
                    AllUserCode+=item["code"]+",";
                }
                tmparr["name"]=item["name"];
                tmparr["title"]=item["name"];
                if(item["users"]){
                    for(let it of item["users"]){
                        item["list"].push(it)
                    }
                }
                if(item["list"] && item["list"].length){
                    tmparr["children"]=  getUserJson(item["list"]);
                    tmpitem.push(tmparr)
                }else{
                    tmpitem.push(tmparr)
                }

            }
            return tmpitem
        }else{
            return null
        }
    }
    //获取所有用户所管理的部门
    function getAllDepartmentUser() {
        let userTree = {};
        $.ajax({
            type: 'get',
            url: 'department/getAllDepartmentUser',
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    userTree = data.data;
                }
            },
            error: function (data) {
            }
        });
        return userTree;

    }
    let treeList = getCurrentDepartmentUser();
    let AlltreeList=getAllDepartmentUser();
    let AllUserTree=getAllJson(AlltreeList.list);
    let userTree = getUserJson(treeList.list);
    //设施切换管理权限者邮箱
    tree.render({
        elem: '#test4'
        ,data: userTree
        ,click: function(obj){
            var code= obj.data.value
            $.ajax({
                url: 'email/cutAcc',
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: {
                    "code":code
                },
                success: function (date) {
                    pop3=date.data;
                    getnoRead()
                    showBox()
                    page();
                    getdeploy()
                },
            });
        }
    });
    //设置内部联系人箱
    tree.render({
        elem: '#test6'
        ,data: AllUserTree
        ,click: function(obj){
            var code= obj.data.value//所属箱子的对象的code
            var box_id="";
            $.ajax({
                url: 'email/getUserBox_id',
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: {
                    "code":code
                },
                success: function (date) {
                    box_id=date.data.box_id;
                    showBoxEmail(box_id,0);
                },
            });
        }

    });

    //监听客户箱点击
    form.on('submit(submitform)', function(data){
        //客户箱展示
        var customsearchs2= $("#customsearchs2").val()
        if(customsearchs2!=null&&customsearchs2!=""){
            var code=""
            var splice = customsearchs2.split(",");
            for(let i in splice){
                var reg = /[^\<>]*\<(.*)\>[^\>]*/;
                var s=splice[i].replace(reg,'$1')
                code+=s+",";
            }
            $.ajax({
                url: 'customer/selectEmailCustomConCateByCode?code='+code,
                type: 'POST',
                success: function (date) {
                    //返回的date，插入树中
                    if(date.data!=null&&date.data!=""){
                        var costomerTree=getEmailCustomerJson(date.data)
                        customerTree(costomerTree)
                    }else{
                        layer.msg("该客户没有联系人")
                    }
                },
            });
        }else{
            layer.msg("查询条件为空，请输入")
        }
    });
    function customerTree(treeDate){
        tree.render({
            elem: '#test5'
            ,data:treeDate
            ,click: function(obj){
                var code= obj.data.value.toString()//所属箱子的对象的code
                if(code.indexOf("start:")!=0){
                    var box_id="";
                    $.ajax({
                        url: 'email/getCustorBox_id',
                        type: 'GET',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: {
                            "email":code
                        },
                        success: function (date) {
                            box_id=date.data.box_id;
                            showBoxEmail(box_id,0);
                        },
                    });
                }else {
                    code=code.split("start:")[1];
                    custorShowEmail(code);
                }

            }
            ,spread:function (obj) {
                alert("进入")
            }
        });
    }




    // 监听菜单点击
    dropdown.onFilter('yidongMenu', function (event) {

    })
    dropdown.onFilter('gengduoMenu', function (event) {
        if(event=="forwarding" || event=="forwardasattachment"){
            parent.intab("views/jsp/BasicData/email/write.jsp","写信")
        }else if(event== "internalforwarding"){
            layer.open({
                type: 2
                ,title: "内部转发、分发"
                ,area:  ['700px', '400px']
                ,btn: ['确定', '取消']
                ,shade: 0.8
                ,btnAlign: 'c'
                ,moveType: 1 //拖拽模式，0或者1
                ,content: "views/jsp/BasicData/email/internalforwarding.jsp"
                ,yes: function(index, layero){
                    var res = window["layui-layer-iframe"+index].callbackdata();
                    if(res.code==""||res.code==null){
                        layer.msg("未选择收件人")
                    }else{
                        var code=res.code;
                        var idea=res.idea;
                        var emails=getEmails();
                        var date={
                            "code":code,
                            "idea":idea,
                            "emails":emails
                        }
                        $.ajax({
                            url: 'email/emailForward',
                            type: 'POST',
                            contentType: "application/json; charset=utf-8",
                            data: JSON.stringify(date),
                            success: function (date) {
                                layer.msg(date.data);
                            },
                        });
                        layer.closeAll();
                    }
                }
            });
        }

    })
    dropdown.onFilter('settingMuen', function (event) {
        var thin = this;
        if(event=="enablefastreading"){
            var lengths = $('a[lay-event='+event+']').children().length;
            if(lengths == 2){
                $('a[lay-event='+event+'] i').empty();
            }else{
                $('a[lay-event='+event+']').append('<i class="layui-icon" style="color: #2e8ffb;">&#xe605;</i>');
            }
        }else if(event=="emailsettings"){
            parent.intab("views/jsp/BasicData/email/setting.jsp","邮件设置")
        }

    })


    dropdown.onFilter('youcanaddemail2', function (event) {
        var id="";
        if(event.indexOf("modifybox")!=-1){
            id=event.split("modifybox")[1]
            event="modifybox";
        }else{
            id=event.split("delbox")[1]
            event="delbox";
        }
        if(event=="modifybox"){
            layer.open({
                type: 2
                ,title:  "修改查询箱"
                ,area:  ['800px', '700px']
                ,shade: 0.8
                ,btnAlign: 'c'
                ,btn: [ '取消','确定']
                ,moveType: 1 //拖拽模式，0或者1
                ,content: ["views/jsp/BasicData/email/gaojiRemove.jsp?boxid="+id,'no']
                ,btn1:function (index,layero) {
                    layer.closeAll();
                }
                ,btn2:function (index,layero) {
                    var res = window["layui-layer-iframe"+index].callbackdata();
                    //打印返回的值，看是否有我们想返回的值。
                    var gaoji={
                        "search_id":res.search_id,
                        "box_id":res.box_id,
                        "boxname":res.boxname,
                        "subject":res.subject,
                        "tag" : res.tag,
                        "recipientName" :res.recipientName,
                        "recipientAddress" :res.recipientAddress,
                        "recDate" : res.recDate,
                        "addresser" : res.addresser,
                        "senderAddresser" : res.senderAddresser,
                        "sendDate" : res.sendDate,
                        "isAdjunct":res.isAdjunct,
                        "adjunct" : res.adjunct,
                        "sub":res.sub,
                        "proPost":proPost
                    }

                    $.ajax({
                        url: 'email/UpdateSearchbox',
                        type: 'GET',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: gaoji,
                        success: function (date) {

                        },
                    });

                }
            });
        }else if(event=="delbox"){
            layer.confirm('真的删除此箱么', function (index) {
                deleteBox(id);
                layer.close(index);
            });
        }
    });
    dropdown.onFilter('youcanaddemail3', function (event) {
        var id="";
        if(event.indexOf("modifybox")!=-1){
            id=event.split("modifybox")[1]
            event="modifybox";
        }else{
            id=event.split("delbox")[1]
            event="delbox";
        }
        if(event=="modifybox"){
            layer.open({
                type: 2
                ,title:  "修改自定义箱"
                ,closeBtn: false
                ,area:  ['800px', '700px']
                ,shade: 0.8
                ,btn: [ '取消','确定']
                ,btnAlign: 'c'
                ,moveType: 1 //拖拽模式，0或者1
                ,content: ["views/jsp/BasicData/email/gaojiRemove.jsp?boxid="+id,'no']
                ,btn1:function (index,layero) {
                    layer.closeAll();
                }
                ,btn2:function (index,layero) {
                    var res = window["layui-layer-iframe"+index].callbackdata();
                    //打印返回的值，看是否有我们想返回的值。
                    var gaoji={
                        "search_id":res.search_id,
                        "box_id":res.box_id,
                        "boxname":res.boxname,
                        "subject":res.subject,
                        "tag" : res.tag,
                        "recipientName" :res.recipientName,
                        "recipientAddress" :res.recipientAddress,
                        "recDate" : res.recDate,
                        "addresser" : res.addresser,
                        "senderAddresser" : res.senderAddresser,
                        "sendDate" : res.sendDate,
                        "isAdjunct":res.isAdjunct,
                        "adjunct" : res.adjunct,
                        "sub":res.sub,
                        "proPost":proPost
                    }

                    $.ajax({
                        url: 'email/UpdateSearchbox',
                        type: 'GET',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: gaoji,
                        success: function (date) {
                        },
                    });

                }
            });
        }else if(event=="delbox"){
            layer.confirm('真的删除此箱么', function (index) {
                //需要删除的ID：data.id
                deleteBox(id);
                layer.close(index);
            });
        }
    });

    dropdown.onFilter("gengduoMenu2", function (event) {

        if(event=="allread"){//全部已读
            $.ajax({
                url: 'email/changeAllEmailReady',
                type: 'get',
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                    layer.msg("修改成功")
                }
            });
        }
        if(event=="incloudAnswer"){//归并已回复
            $.ajax({
                url: 'email/incloudMoreEmails?type=0',
                type: 'get',
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                }
            });
        }
        if(event=="incloudRead"){//归并已读
            $.ajax({
                url: 'email/incloudMoreEmails?type=1',
                type: 'get',
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                }
            });
        }
        if(event=="deleteMuchEmail"){//删除重复邮件
            let index=loadfn(0,"删除中，请等待")
            $.ajax({
                url: 'email/deleteMuchEmail',
                type: 'get',
                success: function (date) {
                    layer.close(index);
                    layer.msg(date.data, {icon:1, time:2000,shift: 6,},function(){
                        window.location.reload();})
                }
            });
        }
    })
    //发送中界面
    function loadfn(n=0) {
        return layer.load(n, {
            content: '发送中...',
            shade: [0.1, '#000'] //0.1透明度的白色背景
        })
    }
    dropdown.onFilter("biaojiMenu", function (event) {
        //event : noready  ready star nostar
        // 这就取决于你点击的是哪一个菜单项了。
        if(event=="noready"){
            var emails = getEmails();
            $.ajax({
                url: 'email/changeEmailReady?type=1',
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(emails),
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                    for(let i in emails){
                        changeWeidu(emails[i].email_id,"bolder")
                    }
                }
            });
        }
        if(event=="ready"){
            var emails = getEmails();
            $.ajax({
                url: 'email/changeEmailReady?type=0',
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(emails),
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                    for(let i in emails){
                        changeWeidu(emails[i].email_id,"normal")
                    }
                }
            });
        }
        if(event=="star"){
            var emails = getEmails();
            $.ajax({
                url: 'email/changeEmailsStar?type=1',
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(emails),
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                }
            });

        }
        if(event=="nostar"){
            var emails = getEmails();
            $.ajax({
                url: 'email/changeEmailsStar?type=0',
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(emails),
                success: function (date) {
                    $(".layui-laypage-btn")[0].click();
                }
            });
        }
    })
    // 输入列表提示
    $('#customsearchs2').tagsInput({
        autocomplete_url: 'customer/selectEmailCustomByDim?type='+type+"&code="+AllUserCode,
        removeWithBackspace: true
    });
    showRemove()
//移动邮件设置
    function  showRemove() {//查看联系人
        $.ajax({
            url: 'email/selectBox',
            type: 'GET',
            success: function (date) {
                var boxs= date.data
                dropdown.suite("#emailMove", {
                    template: "#yidongMenu",
                    success: function ($dom) {
                        var contacts=null;
                        for(let i in boxs){
                            var name=boxs[i].box_name
                            var id=boxs[i].box_id
                            if(boxs[i].box_grade==1){//出示自定义箱和联系人箱？
                                $("#moveEmailBoxs").append("<div class=\"menu-item\">\n" +
                                    "<a href=\"javascript:;\" lay-event=\"alreadysentbox\" onclick='moveEmailForBox(1,"+id+")'><span class=\"\">"+name+"</span></a></div>")
                            }
                            if(boxs[i].box_grade==0){//出示自定义箱和联系人箱？
                                $("#moveEmailPeople").append("<div class=\"menu-item\">\n" +
                                    "<a href=\"javascript:;\" lay-event=\"alreadysentbox\" onclick='moveEmailForBox(0,"+id+")'><span class=\"\">"+name+"</span></a></div>")
                            }

                        }
                        // $("#moveEmailPeople").append( "<dl class=\"layui-nav-child\" style=\"max-height: 300px;overflow: auto\">'+contacts+'</dl>");
                    }
                });

            }
        });
    }
});

//移动邮件
function moveEmailForBox(grade,id) {
    var emails = getEmails();
    $.ajax({
        url: 'email/moveEmailBox?box_id='+id,
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(emails),
        success: function (date) {
            $(".layui-laypage-btn")[0].click();
            layer.msg(date.data)
        }
    });
}
//回复邮件
//回复单人，type=0简单回复，1带全文回复，2带附件文回复
function answer(type) {
    var emails = getEmails();
    if(emails.length>1){
        layer.msg("选择邮件多余1条")
    }else{
        window.location.href="views/jsp/BasicData/email/write.jsp?answer="+type+"&emailID="+emails[0].email_id;
    }

}
//删除箱子
function deleteBox(boxid){
    let index=loadfn(0,"删除中")
    $.ajax({
        url: 'email/deleteBox',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {
            "box_id":boxid
        },
        success: function (date) {
            layer.close(index);
            layer.msg("删除完成", {icon:1, time:2000,shift: 6,},function(){
                window.location.reload();
            })
        },
    });

}
//发送中界面
function loadfn(n=0) {
    return layer.load(n, {
        content: '删除中...',
        shade: [0.1, '#000'] //0.1透明度的白色背景
    })
}
//新增箱子
$(".youcanaddemail").on("click",function () {
    var zdy = $(this).attr("data-type");
    var url = "";
    var title= "";
    var area = ['70%', '60%'];
    if(zdy == "1"){
        url = 'views/jsp/BasicData/email/defineXinxiang.jsp';
        title = "添加内部联系人箱";
    }else if(zdy == "2"){
        url = 'views/jsp/BasicData/email/gaojiIn.jsp';
        title = "添加查询箱";
    }else if(zdy == "3") {
        url = 'views/jsp/BasicData/email/gaojiIn.jsp';
        title = "添加自定义箱";
    }
    layer.open({
        type: 2
        ,title: false //不显示标题栏
        ,closeBtn: false
        ,area:  ['800px', '700px']
        ,shade: 0.8
        ,btn: ['重置', '取消','确定']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,content: [url,'no']
        ,btn2:function (index,layero) {
            layer.closeAll();
        }
        ,btn3:function (index,layero) {
            var res = window["layui-layer-iframe"+index].callbackdata();
            //打印返回的值，看是否有我们想返回的值。
            var gaoji=null;
            if(zdy!=1){
                gaoji = {
                    "zdy":zdy,
                    "boxname":res.boxname,
                    "subject":res.subject,
                    "tag" : res.tag,
                    "recipientName" :res.recipientName,
                    "recipientAddress" :res.recipientAddress,
                    "recDate" : res.recDate,
                    "addresser" : res.addresser,
                    "senderAddresser" : res.senderAddresser,
                    "sendDate" : res.sendDate,
                    "isAdjunct":res.isAdjunct,
                    "adjunct" : res.adjunct,
                    "sub":res.sub,
                    "proPost":proPost
                }
            }
            $.ajax({
                url: 'email/insertSearchbox',
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: gaoji,
                success: function (date) {
                    layer.closeAll();
                    showBox();
                    window.location.reload();　//layer.open关闭刷新
                },

            });
        }
    });

})
var daohang = layui.element;

//箱体显示
function showBox() {
    //先清空再载入  存在问题
    $('#contacts .activelink').on("click",function (e) {
        $("#contacts_content").toggle();
    })
    $('#userBox').find("dl").empty();
    $('#searchBox').find("dl").empty();
    $.ajax({
        url: 'email/selectBox',
        type: 'GET',
        success: function (date) {
            var list = date.data;
            let contacts=""
            let userBox=""
            let searchBox=""
            for (let i in list) {
                if(list[i].box_grade==0){//内部联系人箱
                    // contacts+=" <dd  style=\"display: flex;text-indent:2em;justify-content: space-between\">\n" +
                    //     "                <a href=\"javascript:void(0)\"   onclick='showBoxEmail("+list[i].box_id+",0)'>"+list[i].box_name+"</a>\n" +
                    //     "          <span style='color: darkred' onclick='deleteContacts("+list[i].box_id+")'><i class=\"layui-icon layui-icon-reduce-circle\"></i></span></dd>"
                }else if(list[i].box_grade==1){//自定义箱
                    userBox+=" <dl class=\"layui-nav-child\"><dd  style=\"display: flex;text-indent:2em;justify-content: space-between\">\n" +
                        "                <a href=\"javascript:void(0)\"   onclick='showBoxEmail("+list[i].box_id+",1)'>"+list[i].box_name+"</a>\n" +
                        "            <i class=\"layui-icon layui-icon-more-vertical\"\tstyle=\"margin-right: 10px;cursor: pointer\"  lay-filter=\"youcanaddemail3\"lay-dropdown=\"{menus: [{layIcon:'layui-icon-username',txt: '修改', event:'modifybox"+list[i].box_id+"'},{layIcon: 'layui-icon-set', txt: '删除', event:'delbox"+list[i].box_id+"'}]}\"></i></dd></dl>"
                }else if(list[i].box_grade==2){//查询箱
                    searchBox+=" <dl class=\"layui-nav-child\"><dd  style=\"display: flex;text-indent:2em;justify-content: space-between\">\n" +
                        "                <a href=\"javascript:void(0)\"   onclick='showBoxEmail("+list[i].box_id+",2)'>"+list[i].box_name+"</a>\n" +
                        "            <i class=\"layui-icon layui-icon-more-vertical\"\tstyle=\"margin-right: 10px;cursor: pointer\"  lay-filter=\"youcanaddemail2\"lay-dropdown=\"{menus: [{layIcon:'layui-icon-username',txt: '修改', event:'modifybox"+list[i].box_id+"'},{layIcon: 'layui-icon-set', txt: '删除', event:'delbox"+list[i].box_id+"'}]}\"></i></dd></dl>"
                }
            }
            $('#contacts').append('<dl class="layui-nav-child" style="max-height: 300px;overflow: auto">'+contacts+'</dl>')
            $('#userBox').append(userBox)
            $('#searchBox').append(searchBox)
            daohang.render();
        },
    });
}
function deleteContacts(box_id){
    layer.confirm('真的删除此内部人箱么', function (index) {
        //需要删除的ID：data.id
        deleteBox(box_id)
        layer.close(index);

    });
}


//客户箱邮件分页
function custorShowEmail(code) {
    $.ajax({
        url: 'customer/selectEmailCustomConCateByCode?code='+code,
        type: 'POST',
        success: function (date) {
            debugger
            var data = date.data;
            //复杂的集合体
            var list = data[0]["list"]
            var s="";
            for(let m in list){
                s+=list[m]["email"]+";";
            }
            table.render({
                elem: '#email_table'
                ,url:"email/custorShowEmailByPage"
                ,where: {"code":s,"proPost":proPost}
                ,id: 'email_table'
                ,height: $(document).height() - $('#email_table').offset().top - 50
                ,page: true
                ,limit: 50
                ,limits:[50,100,150,200,250,300,500,1000,1500,2000]
                ,cols: [[
                    {checkbox: true, fixed: true}
                    ,{field:'subject', title:'主题',sort:true,templet: function(element){ return showElement(element) }}
                    ,{field:'senderAddresser', title:'发件人',width:200,sort:true,templet: function(element){
                            if(element.addresser!=""&&element.addresser!=null){
                                return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+element.addresser+"&lt;"+element.senderAddresser+"&gt;";
                            }else{
                                return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+"&lt;"+element.senderAddresser+"&gt;";
                            }
                        }}
                    ,{field:'recipientAddress', title:'收件人',width:180,sort:true}
                    ,{field:'recDate', title:'日期',width:200,sort:true,templet: function(element){
                            return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>&lt;'+element.recDate+'&gt;';
                        }}
                    ,{field:'emailSize', title:'大小',width:150,sort:true,templet: function(element){
                            var size=  (element.emailSize)/1024
                            if(size>1024){
                                size=(size/1024).toFixed(2)+"mb";
                            }else{
                                size=size.toFixed(2)+"kb"
                            }
                            return size
                        }}
                    ,{field:'adjunctNum', title:'附件数',width:100,sort:true}
                ]]
                ,title:"邮件"
                ,done:function (res, curr, count) {
                    donef(res, curr, count);
                }
            });
        },
    });

}
//箱子邮件分页
function showBoxEmail(boxid,grade){
    if(grade==0||grade==1){
        table.render({
            elem: '#email_table'
            ,url:"email/selectBox_emailByPage"
            ,where: {"box_id":boxid,"grade":grade,"proPost":proPost}
            ,id: 'email_table'
            ,height: $(document).height() - $('#email_table').offset().top - 50
            ,page: true
            ,limit: 50
            ,limits:[50,100,150,200,250,300,500,1000,1500,2000]
            ,cols: [[
                {checkbox: true, fixed: true}
                ,{field:'subject', title:'主题',sort:true,templet: function(element){ return showElement(element) }}
                ,{field:'senderAddresser', title:'发件人',width:200,sort:true,templet: function(element){
                        if(element.addresser!=""&&element.addresser!=null){
                            return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+element.addresser+"&lt;"+element.senderAddresser+"&gt;";
                        }else{
                            return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+"&lt;"+element.senderAddresser+"&gt;";
                        }
                    }}
                ,{field:'recipientAddress', title:'收件人',width:180,sort:true}
                ,{field:'recDate', title:'日期',width:200,sort:true,templet: function(element){
                        return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>&lt;'+element.recDate+'&gt;';
                    }}
                ,{field:'emailSize', title:'大小',width:150,sort:true,templet: function(element){
                        var size=  (element.emailSize)/1024
                        if(size>1024){
                            size=(size/1024).toFixed(2)+"mb";
                        }else{
                            size=size.toFixed(2)+"kb"
                        }
                        return size
                    }}
                ,{field:'adjunctNum', title:'附件数',width:100,sort:true}
            ]]
            ,toolbar: "<div>用户表:未读邮件"+noready+"封</div>"
            ,title:"邮件"
            ,done:function (res, curr, count) {
                donef(res, curr, count);
            }
        });
    }else{
        $.ajax({
            url: 'email/selectSearch',
            type: 'get',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data:  {"box_id":boxid,"grade":grade},
            success: function (date) {
                var search=date.data
                table.render({
                    elem: '#email_table'
                    ,url:"email/selectBox_email1ByPage?pop3id="+pop3+"&proPost="+proPost
                    ,where:search
                    ,id: 'email_table'
                    ,height: $(document).height() - $('#email_table').offset().top - 50
                    ,page: true
                    ,limit: 50
                    ,limits:[50,100,150,200,250,300,500,1000,1500,2000]
                    ,cols: [[
                        {checkbox: true, fixed: true}
                        ,{field:'subject', title:'主题',sort:true,templet: function(element){ return showElement(element) }}
                        ,{field:'senderAddresser', title:'发件人',width:200,sort:true,templet: function(element){
                                if(element.addresser!=""&&element.addresser!=null){
                                    return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+element.addresser+"&lt;"+element.senderAddresser+"&gt;";
                                }else{
                                    return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>'+"&lt;"+element.senderAddresser+"&gt;";
                                }
                            }}
                        ,{field:'recipientAddress', title:'收件人',width:180,sort:true}
                        ,{field:'recDate', title:'日期',width:200,sort:true,templet: function(element){
                                return '<i style="color:blue;">&#xe608;</i><i>&#xe66d;</i>&lt;'+element.recDate+'&gt;';
                            }}
                        ,{field:'emailSize', title:'大小',width:100,sort:true,templet: function(element){
                                var size=  (element.emailSize)/1024
                                if(size>1024){
                                    size=(size/1024).toFixed(2)+"mb";
                                }else{
                                    size=size.toFixed(2)+"kb"
                                }
                                return size
                            }}
                        ,{field:'adjunctNum', title:'附件数',width:100,sort:true}
                    ]]
                    ,toolbar: "<div>用户表:未读邮件"+noready+"封</div>"
                    ,title:"邮件"
                    ,done:function (res, curr, count) {
                        donef(res, curr, count);
                    }
                });

            },

        });
    }

}

//多email操作  上面的操作
//归并操作
$("#incloud").on("click",function () {
    inclouding();
})
function inclouding() {
    layer.open({
        type: 2
        ,title: "是否归并邮件" //不显示标题栏
        ,closeBtn: false
        ,area:  ['200px', '100px']
        ,shade: 0.8
        ,btn: ['确认', '取消']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,btn1:function (index,layero) {
            var emails=getEmails();
            $.ajax({
                url: 'email/incloudEmail',
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(emails),
                success: function (date) {
                    layer.closeAll()
                    $(".layui-laypage-btn")[0].click();
                    layer.msg(date.data)

                },

            });
        }});

}
$("#deleteEmails").on("click",function () {
    changeEmailsClass(7);//修改为回收文件
})

$("#putLitter").on("click",function () {
    changeEmailsClass(6);//修改为垃圾邮件
})
function changeEmailsClass(emailClass) {
    emails=getEmails();
    $.ajax({
        url: 'email/changeEmailsClass?emailClass='+emailClass,
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(emails),
        success: function (date) {
            $(".layui-laypage-btn")[0].click();
        }
    });

}
$("#shouxin").on("click",function () {
    $.ajax({
        url: 'email/GetEmailOme',
        type: 'GET',
        success: function (date) {
            if(date.data=="success"){
                layer.msg("已完成收信")
                window.location.reload()
            }else{
                layer.msg(date.data+"账号设置已被更改，无法收信", {
                    icon: 1,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                }, function(){
                    window.location.reload()
                });
            }


        }
    });
})

$("#fresh").on("click",function () {
    window.location.reload()
})
function getEmails() {
    var checkStatus = table.checkStatus('email_table'); //即为基础参数 id 对应的值
    var emails=new Array();
    if(checkStatus.data.length>0){
        var ems=checkStatus.data;
        for(let i in ems){
            emails.push(ems[i])
        }}
    return emails;
}

function resetControl(type) {
    yidongControl=type;
}


